"""
视频流相关的数据模型定义
"""
from datetime import datetime
from typing import Optional, List, Dict, Any
from pydantic import BaseModel, Field, model_validator
from enum import Enum


class StreamProtocol(str, Enum):
    """视频流协议枚举"""
    RTSP = "rtsp"
    HLS = "hls"
    WEBRTC = "webrtc"
    HTTP_FLV = "http-flv"
    WEBSOCKET = "websocket"


class StreamQuality(str, Enum):
    """视频流质量枚举"""
    AUTO = "auto"
    HIGH = "high"
    MEDIUM = "medium"
    LOW = "low"


class VideoStreamRequest(BaseModel):
    """视频流请求模型"""
    camera_id: str = Field(..., description="摄像头ID")
    protocol: StreamProtocol = Field(StreamProtocol.HLS, description="流协议")
    quality: StreamQuality = Field(StreamQuality.AUTO, description="视频质量")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "camera_id": "camera_001",
                "protocol": "hls",
                "quality": "auto"
            }
        }
    }


class VideoStreamResponse(BaseModel):
    """视频流响应模型"""
    camera_id: str = Field(..., description="摄像头ID")
    stream_url: str = Field(..., description="视频流地址")
    protocol: StreamProtocol = Field(..., description="流协议")
    quality: StreamQuality = Field(..., description="视频质量")
    resolution: Optional[str] = Field(None, description="分辨率")
    bitrate: Optional[int] = Field(None, description="码率(kbps)")
    fps: Optional[int] = Field(None, description="帧率")
    expires_at: Optional[datetime] = Field(None, description="过期时间")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "camera_id": "camera_001",
                "stream_url": "https://example.com/stream/camera_001/index.m3u8",
                "protocol": "hls",
                "quality": "high",
                "resolution": "1920x1080",
                "bitrate": 2000,
                "fps": 25,
                "expires_at": "2024-01-01T12:00:00Z"
            }
        }
    }


class VideoSnapshotRequest(BaseModel):
    """视频截图请求模型"""
    camera_id: str = Field(..., description="摄像头ID")
    width: Optional[int] = Field(None, ge=100, le=3840, description="截图宽度")
    height: Optional[int] = Field(None, ge=100, le=2160, description="截图高度")
    quality: Optional[int] = Field(90, ge=1, le=100, description="图片质量(1-100)")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "camera_id": "camera_001",
                "width": 1280,
                "height": 720,
                "quality": 90
            }
        }
    }


class VideoSnapshotResponse(BaseModel):
    """视频截图响应模型"""
    camera_id: str = Field(..., description="摄像头ID")
    snapshot_url: str = Field(..., description="截图地址")
    width: int = Field(..., description="截图宽度")
    height: int = Field(..., description="截图高度")
    file_size: int = Field(..., description="文件大小(字节)")
    created_at: datetime = Field(..., description="创建时间")
    expires_at: Optional[datetime] = Field(None, description="过期时间")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "camera_id": "camera_001",
                "snapshot_url": "https://example.com/snapshots/camera_001_20240101120000.jpg",
                "width": 1280,
                "height": 720,
                "file_size": 245760,
                "created_at": "2024-01-01T12:00:00Z",
                "expires_at": "2024-01-02T12:00:00Z"
            }
        }
    }


class VideoRecordRequest(BaseModel):
    """视频录像请求模型"""
    camera_id: str = Field(..., description="摄像头ID")
    start_time: datetime = Field(..., description="开始时间")
    end_time: datetime = Field(..., description="结束时间")
    quality: StreamQuality = Field(StreamQuality.AUTO, description="录像质量")
    
    @model_validator(mode='after')
    def validate_time_range(self) -> 'VideoRecordRequest':
        if self.end_time <= self.start_time:
            raise ValueError('结束时间必须大于开始时间')
        return self
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "camera_id": "camera_001",
                "start_time": "2024-01-01T10:00:00Z",
                "end_time": "2024-01-01T11:00:00Z",
                "quality": "high"
            }
        }
    }


class VideoRecordResponse(BaseModel):
    """视频录像响应模型"""
    camera_id: str = Field(..., description="摄像头ID")
    record_url: str = Field(..., description="录像地址")
    start_time: datetime = Field(..., description="开始时间")
    end_time: datetime = Field(..., description="结束时间")
    duration: int = Field(..., description="时长(秒)")
    file_size: Optional[int] = Field(None, description="文件大小(字节)")
    quality: StreamQuality = Field(..., description="录像质量")
    created_at: datetime = Field(..., description="创建时间")
    expires_at: Optional[datetime] = Field(None, description="过期时间")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "camera_id": "camera_001",
                "record_url": "https://example.com/records/camera_001_20240101100000.mp4",
                "start_time": "2024-01-01T10:00:00Z",
                "end_time": "2024-01-01T11:00:00Z",
                "duration": 3600,
                "file_size": 1073741824,
                "quality": "high",
                "created_at": "2024-01-01T12:00:00Z",
                "expires_at": "2024-01-08T12:00:00Z"
            }
        }
    }


class StreamQualityInfo(BaseModel):
    """流质量信息模型"""
    quality: StreamQuality = Field(..., description="质量等级")
    resolution: str = Field(..., description="分辨率")
    bitrate: int = Field(..., description="码率(kbps)")
    fps: int = Field(..., description="帧率")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "quality": "high",
                "resolution": "1920x1080",
                "bitrate": 2000,
                "fps": 25
            }
        }
    }


class VideoStreamStatus(BaseModel):
    """视频流状态模型"""
    camera_id: str = Field(..., description="摄像头ID")
    is_online: bool = Field(..., description="是否在线")
    current_viewers: int = Field(0, description="当前观看人数")
    available_qualities: List[StreamQualityInfo] = Field([], description="可用质量")
    last_frame_time: Optional[datetime] = Field(None, description="最后一帧时间")
    error_message: Optional[str] = Field(None, description="错误信息")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "camera_id": "camera_001",
                "is_online": True,
                "current_viewers": 5,
                "available_qualities": [
                    {
                        "quality": "high",
                        "resolution": "1920x1080",
                        "bitrate": 2000,
                        "fps": 25
                    }
                ],
                "last_frame_time": "2024-01-01T12:00:00Z",
                "error_message": None
            }
        }
    }


class MultiStreamRequest(BaseModel):
    """多路视频流请求模型"""
    camera_ids: List[str] = Field(..., min_length=1, max_length=16, description="摄像头ID列表")
    protocol: StreamProtocol = Field(StreamProtocol.HLS, description="流协议")
    quality: StreamQuality = Field(StreamQuality.AUTO, description="视频质量")
    layout: Optional[str] = Field("auto", description="布局方式")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "camera_ids": ["camera_001", "camera_002", "camera_003", "camera_004"],
                "protocol": "hls",
                "quality": "medium",
                "layout": "2x2"
            }
        }
    }


class MultiStreamResponse(BaseModel):
    """多路视频流响应模型"""
    streams: List[VideoStreamResponse] = Field(..., description="视频流列表")
    layout: str = Field(..., description="布局方式")
    total_count: int = Field(..., description="总数量")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "streams": [
                    {
                        "camera_id": "camera_001",
                        "stream_url": "https://example.com/stream/camera_001/index.m3u8",
                        "protocol": "hls",
                        "quality": "medium",
                        "resolution": "1280x720",
                        "bitrate": 1000,
                        "fps": 25
                    }
                ],
                "layout": "2x2",
                "total_count": 4
            }
        }
    }


class StreamStatistics(BaseModel):
    """流统计信息模型"""
    camera_id: str = Field(..., description="摄像头ID")
    total_viewers: int = Field(0, description="总观看人数")
    peak_viewers: int = Field(0, description="峰值观看人数")
    total_duration: int = Field(0, description="总播放时长(秒)")
    bytes_sent: int = Field(0, description="发送字节数")
    frames_sent: int = Field(0, description="发送帧数")
    error_count: int = Field(0, description="错误次数")
    last_error: Optional[str] = Field(None, description="最后错误")
    created_at: datetime = Field(..., description="统计开始时间")
    updated_at: datetime = Field(..., description="最后更新时间")
    
    model_config = {
        "json_schema_extra": {
            "example": {
                "camera_id": "camera_001",
                "total_viewers": 25,
                "peak_viewers": 8,
                "total_duration": 86400,
                "bytes_sent": 1073741824,
                "frames_sent": 2160000,
                "error_count": 3,
                "last_error": "Connection timeout",
                "created_at": "2024-01-01T00:00:00Z",
                "updated_at": "2024-01-01T12:00:00Z"
            }
        }
    }